import { getToken, setToken, removeToken } from '@/utils/auth'
import { getInfo, logout } from '@/api/user'
import { login } from '@/api/user'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken('token') || '',
    uesrInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    // 清空token的函数
    delToken(state) {
      state.token = ''
      removeToken()
    },
    updateUpdateToken(state, info) {
      state.uesrInfo = info
    },
    delUserInfo(state) {
      state.uesrInfo = {}
    }
  },
  actions: {
    async initToken(context, formDate) {
      const res = await login(formDate)
      // console.log(res)
      // 判断是否登录成功，提示用户
      if (res.code !== 10000) {
        return Message.error(res.message)
      }
      Message.success(res.message)
      context.commit('updateToken', res.data)
    },
    async getUserInfo(context) {
      try {
        const res = await getInfo()
        const info = await logout(res.data.userId)
        context.commit('updateUpdateToken', { ...res.data, ...info.data })
        // console.log(res)
        // 返回权限信息
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      // 重置路由
      resetRouter()
    }
  }
}
